<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i>
                    {{pageTitle}}
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <acc-set-card></acc-set-card>
        <div class="container" :style="{'min-height': containerHeight + 'px'}">
            <div class="handle-box flex flex-center">
                <el-button type="primary" icon="el-icon-folder" @click="saveEdit()">保存</el-button>
            </div>

            <el-form label-width="100px" :rules="rules" :model="ruleForm" ref="ruleForm">
                <el-row>
                    <el-col :sm="20" :md="5">
                        <el-form-item label="单号" prop="billId">
                            <el-input v-model="ruleForm.billId" disabled placeholder="保存后自动生成"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :sm="20" :md="5">
                        <el-form-item label="单别名称" prop="orderNoCode">
                            <div @click="showTreeDialogSingle('单别')" v-if="!isUpdate">
                                <el-input v-model="ruleForm.orderNoCode" placeholder="请输入">
                                    <i slot="suffix" class="el-icon-search"></i>
                                </el-input>
                            </div>
                            <div v-if="isUpdate">
                                <el-input v-model="ruleForm.orderNoCode" disabled placeholder="请输入">
                                    <i slot="suffix" class="el-icon-search"></i>
                                </el-input>
                            </div>
                        </el-form-item>
                    </el-col>

                    <el-col :sm="20" :md="5">
                        <el-form-item label="日期" prop="billDate">
                            <el-date-picker
                                v-model="ruleForm.billDate"
                                type="date"
                                placeholder="选择日期"
                                clearable
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :sm="20" :md="5">
                        <el-form-item label="人员" prop="empName">
                            <div @click="showTreeDialog1('人员')">
                                <el-input v-model="ruleForm.empName" placeholder="请输入">
                                    <i slot="suffix" class="el-icon-search"></i>
                                </el-input>
                            </div>
                        </el-form-item>
                    </el-col>

                    <el-col :sm="20" :md="5">
                        <el-form-item label="部门" prop="deptName">
                            <el-input v-model="ruleForm.deptName" disabled></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :sm="20" :md="5">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="ruleForm.remark" maxlength="120" show-word-limit></el-input>
                        </el-form-item>
                    </el-col>

                    <!-- <el-col :sm="20" :md="6" align="center">
                            <el-button @click="handleClose">取 消</el-button>
                            <el-button type="primary" @click="submitForm('ruleForm')">保 存</el-button>
                    </el-col>-->
                </el-row>
            </el-form>
            <div class="handler-box">
                <vxe-toolbar>
                    <template v-slot:buttons>
                        <vxe-button status="primary" icon="fa fa-plus" @click="insertEvent(-1)">新增行</vxe-button>
                        <vxe-button status="danger" @click="deleteCheckBoxRow()">删除选中行</vxe-button>
                    </template>
                </vxe-toolbar>
                <vxe-table
                    keep-source
                    stripe
                    border
                    resizable
                    :auto-resize="true"
                    ref="xTable"
                    height="400"
                    :data="billBankDetails"
                    :edit-rules="validRules"
                    :mouse-config="{selected: true}"
                    :keyboard-config="{isArrow: true, isDel: true, isEnter: true, isTab: true, isEdit: true}"
                    :edit-config="{trigger: 'dblclick', mode: 'cell'}"
                >
                    <vxe-table-column type="checkbox" width="60"></vxe-table-column>
                    <vxe-table-column type="seq" width="60"></vxe-table-column>
                    <vxe-table-column
                        field="snNo"
                        title="项次"
                        width="80"
                        :edit-render="{name: '$input', props: {type: 'number',min:1}}"
                    ></vxe-table-column>
                    <vxe-table-column
                        field="accBankId"
                        title="银行账号"
                        :edit-render="{name: 'input',events: {focus: bankFocusEvent}, attrs: {type: 'text',readonly:true}}"
                    ></vxe-table-column>
                    <vxe-table-column
                        field="description"
                        title="账号名称"
                        :edit-render="{name: 'input', attrs: {type: 'text',disabled: true}}"
                    ></vxe-table-column>
                    <vxe-table-column
                        field="tranFlag"
                        title="收支类型"
                        :edit-render="{name: '$select', options: tranFlagList}"
                    ></vxe-table-column>
                    <vxe-table-column
                        field="currCode"
                        title="币别"
                        :edit-render="{name: 'input', attrs: {type: 'text',disabled: true}}"
                    ></vxe-table-column>
                    <vxe-table-column
                        field="amount"
                        title="金额"
                        :edit-render="{name: '$input',events: {change: countAmount}, props: {type: 'float', digits: 2,min:1}}"
                    ></vxe-table-column>
                    <vxe-table-column
                        field="subCode"
                        title="科目"
                        :edit-render="{name: 'input', attrs: {type: 'text',disabled: true}}"
                    ></vxe-table-column>
                    <vxe-table-column
                        field="adSubCode"
                        title="对方科目"
                        :edit-render="{name: 'input',events: {focus: adSubFocusEvent}, attrs: {type: 'text'}}"
                    ></vxe-table-column>
                    <vxe-table-column
                        field="remark"
                        title="摘要说明"
                        :edit-render="{name: 'input', attrs: {type: 'text'}}"
                    ></vxe-table-column>
                    <vxe-table-column
                        field="currRate"
                        title="汇率"
                        :edit-render="{name: 'input', attrs: {type: 'text',disabled: true}}"
                    ></vxe-table-column>
                    <vxe-table-column
                        field="lamount"
                        title="本币金额"
                        :edit-render="{name: '$input', props: {type: 'float', digits: 2,min:1,disabled: true}}"
                    ></vxe-table-column>
                </vxe-table>
            </div>
        </div>

        <!-- 人员搜索 -->
        <tree-search
            :isShow="showSearch1"
            :dialogTitle="searchDialogTit1"
            @edit="searchBack1"
            @close="closeTreeDialog1"
        ></tree-search>

        <!-- 新增-对方科目搜索 -->
        <tree-search-subject
            :isShow="showSearchSub"
            :dialogTitle="searchDialogTitSub"
            @edit="searchBackSub"
            @close="closeTreeDialogSub"
        ></tree-search-subject>
        <!-- 新增-银行账户搜索 -->
        <table-search-bank
            :isShow="showSearchBank"
            :dialogTitle="searchDialogTitBank"
            @edit="searchBackBank"
            @close="closeTreeDialogBank"
        ></table-search-bank>
        <!-- 新增-单别查询搜索 -->
        <table-search-singleset
            :isShow="showSearchSingle"
            :dialogTitle="searchDialogTitSingle"
            @edit="searchBackSingle"
            @close="closeTreeDialogSingle"
        ></table-search-singleset>
    </div>
</template>


<script>
import appMain from '../../../utils/app_main';
import _ from 'lodash';
import XEUtils from 'xe-utils';

export default {
    data() {
        return {
            pageTitle: '',
            containerHeight: '',
            //新增明细列表
            billBankDetails: [],
            searchDialogTit1: '',
            showSearch1: false,
            searchDialogTit2: '',
            showSearch2: false,
            searchDialogTitSub: '',
            showSearchSub: false,
            searchDialogTitBank: '',
            showSearchBank: false,
            searchDialogTitSingle: '',
            showSearchSingle: false,
            //会计期间
            orderNoList: [],
            rules: {
                empName: [{ required: true, message: '请选择', trigger: 'change' }],
                orderNoCode: [{ required: true, message: '请选择', trigger: 'change' }],
                billDate: [{ required: true, message: '请选择', trigger: 'change' }]
            },
            validRules: {
                snNo: [
                    { required: true, message: '项次必须填写' },
                    { pattern: '^[0-9]{1,18}$', message: '格式不正确,必须为数字' }
                ],
                amount: [{ required: true, message: '金额必须填写' }],
                adSubId: [{ required: true, message: '必须填写' }],
                accBankId: [{ required: true, message: '必须填写' }],
                remark: [{ min: 0, max: 250, message: '长度在 0 到 250 个字符' }]
            },
            dialogVisible: false, //新增
            dialogVisibleEdit: false, //编辑科目
            ruleForm: {
                billDate: '', //日期
                deptId: '', //部门id
                deptName: '', //部门名称
                empId: '', //人员id
                empName: '', //人员姓名
                orderNoCode: '', //单别代码
                orderNoId: '', //单别id
                remark: '' //备注说明
            }, //新增model
            editForm: {},
            tranFlagList: [
                {
                    label: '收入',
                    value: '1'
                },
                {
                    label: '支出',
                    value: '-1'
                }
            ],
            //新增,在编辑的明细行
            editRow: '',
            isUpdate: false
        };
    },
    created() {
        //如果有id过来就是修改的
        if (this.$route.query.id) {
            let id = this.$route.query.id;
            //是更新操作
            this.isUpdate = true;
            //查询银行往来信息
            this.getDetailById(id);
        } else {
            //新增操作
            this.isUpdate = false;
        }
    },
    mounted() {
        var div_height = window.screen.availHeight;
        var height = div_height - 100;
        this.containerHeight = height - 200;
        this.pageTitle = this.$router.currentRoute.meta.title;
        //$refs.xTree.setAllTreeExpand(true);
    },
    methods: {
        async addRate() {
            let updateRecords = this.$refs.xTable.tableData;
            const errMap = await this.$refs.xTable.validate(updateRecords).catch(errMap => errMap);
            if (errMap) {
                this.$message.warning('请按要求填写明细！');
                return;
            }
            let params = {
                billBankDetails: this.billBankDetails,
                billBankMaster: this.ruleForm
            };
            appMain
                .billBankDetailInsert(params)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.$message.success(res.data.message);

                        this.$router.push({
                            path: '/bankTransactionList' //跳转的路径
                        });
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        async updateRate() {
            let updateRecords = this.$refs.xTable.tableData;
            const errMap = await this.$refs.xTable.validate(updateRecords).catch(errMap => errMap);
            if (errMap) {
                this.$message.warning('请按要求填写明细！');
                return;
            }
            let params = {
                billBankDetails: this.billBankDetails,
                billBankMaster: this.ruleForm
            };
            appMain
                .billBankDetailUpdateById(params)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.$message.success(res.data.message);
                        this.$router.push({
                            path: '/bankTransactionList' //跳转的路径
                        });
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },

        getDetailById(billId) {
            appMain
                .billBankDetailFindById({}, billId)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.billBankDetails = res.data.data.billBankDetails;
                        this.ruleForm = res.data.data.billBankMaster;
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        saveEdit() {
            if (this.isUpdate == false) {
                this.submitForm('ruleForm');
            } else if (this.isUpdate == true) {
                this.submitForm('editForm');
            }
        },
        submitForm(formName) {
            console.log('submit', this.$refs);
            this.$refs['ruleForm'].validate(valid => {
                if (valid) {
                    if (formName == 'searchRuleForm') {
                        //新增科目
                        this.getData();
                    } else if (formName == 'ruleForm') {
                        this.addRate();
                    } else if (formName == 'editForm') {
                        this.updateRate();
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },

        showTreeDialog1(tit) {
            console.log('showTreeDialog1');
            this.searchDialogTit1 = tit;
            this.showSearch1 = true;
        },
        // 树组件搜索结果返回
        searchBack1(data) {
            this.ruleForm.empName = data.backData.name;
            this.ruleForm.empId = data.backData.id;
            this.ruleForm.deptName = data.backData.organizationName;
            this.ruleForm.deptId = data.backData.organizationId;

            this.showSearch1 = false;
        },
        closeTreeDialog1(data) {
            this.showSearch1 = data.showDialog;
        },

        // 科目树组件搜索结果返回
        searchBackSub(data) {
            console.log(data.backData, 'searchTreeBackSub');
            this.billBankDetails[this.editRow].adSubId = data.backData.id;
            this.billBankDetails[this.editRow].adSubCode = data.backData.subCode;
            this.billBankDetails[this.editRow].adSubName = data.backData.subName;
            this.showSearchSub = false;
        },
        closeTreeDialogSub(data) {
            this.showSearchSub = data.showDialog;
        },
        adSubFocusEvent({ rowIndex }) {
            console.log('adSubFocusEvent', rowIndex);
            this.editRow = rowIndex;
            this.searchDialogTitSub = '对方科目';
            this.showSearchSub = true;
        },
        // 科目树组件搜索结果返回
        searchBackBank(data) {
            console.log(data.backData, 'searchTreeBackBank');
            this.billBankDetails[this.editRow].subId = data.backData.subId;
            this.billBankDetails[this.editRow].subCode = data.backData.subCode;
            this.billBankDetails[this.editRow].subName = data.backData.subName;
            // this.billBankDetails[this.editRow].currId = data.backData.curreny;
            this.billBankDetails[this.editRow].accBankId = data.backData.id;
            this.billBankDetails[this.editRow].bankAccount = data.backData.bankAccount;
            this.billBankDetails[this.editRow].description = data.backData.bankName;
            this.getByCurrCodeAndDate(data.backData.curreny, this.ruleForm.billDate);
            this.showSearchBank = false;
        },
        //获取费率
        getByCurrCodeAndDate(currCode, date) {
            let params = {
                currCode: currCode,
                date: date
            };
            appMain
                .getByCurrCodeAndDate(params)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.billBankDetails[this.editRow].currId = res.data.data.id;
                        this.billBankDetails[this.editRow].currCode = res.data.data.currCode;
                        this.billBankDetails[this.editRow].currRate = res.data.data.rate;
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        closeTreeDialogBank(data) {
            this.showSearchBank = data.showDialog;
        },
        bankFocusEvent({ rowIndex }) {
            console.log('adSubFocusEvent', rowIndex);
            if (this.ruleForm.billDate == '') {
                this.$message.info('请先选择日期');
                return;
            }
            this.editRow = rowIndex;
            this.searchDialogTitBank = '银行账户';
            this.showSearchBank = true;
        },

        showTreeDialogSingle(tit) {
            console.log('showTreeDialogSingle');
            this.searchDialogTitSingle = tit;
            this.showSearchSingle = true;
        },
        // 单别树组件搜索结果返回
        searchBackSingle(data) {
            console.log(data.backData, 'searchTreeBackSingle');

            this.ruleForm.orderNoId = data.backData.id;
            this.ruleForm.orderNoCode = data.backData.ruleCode;
            this.ruleForm.orderRuleName = data.backData.ruleName;
            this.showSearchSingle = false;
        },
        closeTreeDialogSingle(data) {
            this.showSearchSingle = data.showDialog;
        },

        /**vxe-table */
        async insertEvent(row) {
            let length = this.$refs.xTable.tableData.length + 1;
            let record = {
                accBankId: '', //银行账号代码
                description: '', //银行账号名称
                adSubId: '', //对方会计科目代码
                amount: '', //原币金额
                billId: '', //银行流水单号
                currId: '', //币别:默认 CNY
                currRate: 1, //汇率
                detailBillId: '', //明细银行流水单号
                lamount: '', //本币金额
                orderNoCode: '', //单别
                orderNoId: '', //单别id
                remark: '', //备注
                snNo: length, //明细序号
                subId: '', //会计科目代码
                tranFlag: '1' //收支类型: 1 收入,-1支出
            };

            let { row: newRow } = await this.$refs.xTable.insertAt(record, row);
            //await this.$refs.xTable.setActiveCell(newRow, 'sex');
            console.log('insertEvent', this.$refs.xTable.tableData);
            console.log('insertEvent', this.billBankDetails);
            this.billBankDetails = this.$refs.xTable.tableData;
        },
        //删除选中列
        deleteCheckBoxRow() {
            let selectRecords = this.$refs.xTable.getCheckboxRecords();
            if (selectRecords.length < 1) {
                this.$message({
                    message: '请选择一条数据',
                    type: 'info'
                });
            } else {
                this.$refs.xTable.removeCheckboxRow();
                this.billBankDetails = this.$refs.xTable.tableData;
            }
        },
        countAmount(obj) {
            console.log('countAmount', obj.row);
            //let mount = XEUtils.multiply(obj.row.amount, obj.row.currRate);
            //console.log('countAmount mount', mount);
            //this.billBankDetails[obj.rowIndex].lamount = mount;
            this.countLamount(obj.row.amount, obj.row.currRate);
        },
        countLamount(amount, currRate) {
            let params = {
                amount: amount,
                currRate: currRate
            };
            appMain
                .countLamount(params)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.billBankDetails[this.editRow].lamount = res.data.data;
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        }
    },
    computed: {},
    watch: {}
};
</script>

<style lang="css" scoped>
.el-card {
    height: 100%;
}

.flex-right {
    padding: 20px;
}

.handler-box {
    border: 1px solid rgb(232, 234, 236);
    padding: 5px;
    margin-bottom: 15px;
}

.tree-box .flex-left {
    padding: 0px !important;
}

.el-date-editor {
    width: 100%;
}

.vxe-select--panel {
    z-index: 9997 !important;
}
.vxe-input--panel.type--date,
.vxe-input--panel.type--month,
.vxe-input--panel.type--week,
.vxe-input--panel.type--year {
    z-index: 9998 !important;
}

.vxe-table--tooltip-wrapper,
.theme--dark,
.placement--top,
.is--visible,
.vxe-table--valid-error {
    z-index: 9998 !important;
}

.vxe-table--ignore-clear,
.vxe-select--panel,
.is--transfer {
    z-index: 9998 !important;
}
.vxe-select-option--wrapper,
.vxe-select-option {
    z-index: 9998 !important;
}

.handle-box {
    padding: 5px 50px;
    width: 100%;
    background-color: #fff;
    position: absolute;
    left: 0;
    bottom: 0px;
    border-bottom: 1px solid #ddd;
    border-top: 1px solid #ddd;
    z-index: 1;
}
</style>